//
//  PictureViewController.m
//  MilitaryDemo
//
//  Created by qianfeng01 on 15-7-4.
//  Copyright (c) 2015年 qianfeng01. All rights reserved.
//

#import "PictureViewController.h"
#import "PicsCell1.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "PicsModel.h"
#import "PictureDetailViewController.h"
#import "JHRefresh.h"
@interface PictureViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property(nonatomic,strong)UICollectionView *collectionView;

@end

@implementation PictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self creatCollectionView];
    [self firstDownload];
    [self creatRefreshView];
    //[self downloadImages];
}

-(void)creatCollectionView
{
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc]init];
     [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    // 对于垂直滚动，上下cell的间距，对于水平滚动，左右cell的间距 最小间距
     flowLayout.minimumLineSpacing = 10;
    
    // 设置item之间间距，实际间隔需要根据item的size和edgesInsets的值来调节
    flowLayout.minimumInteritemSpacing = 0;
    
    // 全局设置itemSize
    flowLayout.itemSize = CGSizeMake(kScreenSize.width, kScreenSize.height/3);
    
    // 内边距
    //flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width,kScreenSize.height-64) collectionViewLayout:flowLayout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    self.collectionView.backgroundColor=[UIColor whiteColor];
    [_collectionView registerNib:[UINib nibWithNibName:@"PicsCell1" bundle:nil] forCellWithReuseIdentifier:@"PicsCell1"];
    [self.view addSubview:_collectionView];
}
-(void)creatRefreshView
{
    __weak typeof (self) weakSelf = self;
    [weakSelf.collectionView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing=YES;
        weakSelf.currentPage=1;
        NSString *url=[NSString stringWithFormat:KPicsUrl,weakSelf.currentPage];
        [weakSelf addTaskWithUrl:url isRefresh:YES];
        
    }];
    [weakSelf.collectionView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class]  beginRefresh:^{
        if (weakSelf.isLoadMore) {
            return;
        }
        weakSelf.isLoadMore=YES;
        weakSelf.currentPage++;
        NSString *url=[NSString stringWithFormat:KPicsUrl,weakSelf.currentPage];
        [weakSelf addTaskWithUrl:url isRefresh:YES];
    }];
}
- (void)endRefreshing {
    if (self.isRefreshing) {
        self.isRefreshing = NO;//标记刷新结束
        //正在刷新 就结束刷新
        [self.collectionView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
    if (self.isLoadMore) {
        self.isLoadMore = NO;
        [self.collectionView footerEndRefreshing];
    }
}
-(void)firstDownload
{
    self.currentPage=1;
    [self addTaskWithUrl:[NSString stringWithFormat:KPicsUrl,self.currentPage] isRefresh:NO];
}
-(void)addTaskWithUrl:(NSString *)url isRefresh:(BOOL)isRefresh
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    __weak typeof (self) weakSelf=self;
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (self.currentPage == 1) {
            [self.dataArr removeAllObjects];
        }
        NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *ImglistArr=dict[@"imglist"];
        for (NSDictionary *imgDict in ImglistArr) {
            PicsModel *model=[[PicsModel alloc]init];
            [model setValuesForKeysWithDictionary:imgDict];
            [weakSelf.dataArr addObject:model];
        }
        [weakSelf.collectionView reloadData];
        [weakSelf endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"图片数据下载错误");
    }];
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PicsCell1 *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"PicsCell1" forIndexPath:indexPath];
    PicsModel *model=self.dataArr[indexPath.row];

    [cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:model.imgurls.lastObject]placeholderImage:[UIImage imageNamed:@"zhanwei"]];
    cell.titleLabel.text=model.title;
    return cell;
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    PictureDetailViewController *controller=[[PictureDetailViewController alloc]init];
    PicsModel *model=self.dataArr[indexPath.row];
    controller.hidesBottomBarWhenPushed=YES;
    controller.id=model.id;
    controller.Pictitle=model.title;
    [self.navigationController pushViewController:controller animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
